package 锁;

/**
 * 自旋锁策略模板
 */
public abstract class SpinRedisLockStrategy implements DistributedLock {

    private static final Integer retry = 50; //默认重试5次
    private static final Long sleeptime = 100L;
    protected String lockKey;
    protected String requestId;
    protected int expireTime;

    private SpinRedisLockStrategy() {
    }

    public SpinRedisLockStrategy(String lockKey, String requestId, int expireTime) {
        this.lockKey = lockKey;
        this.requestId = requestId;
        this.expireTime = expireTime;
    }

    /**
     * 模板方法，搭建的获取锁的框架，具体逻辑交于子类实现
     */
    @Override
    public boolean lock() {
        Boolean flag = false;
        try {
            for (int i = 0; i < retry; i++) {
                flag = tryLock();
                if (flag) {
                    System.out.println(Thread.currentThread().getName() + "获取锁成功");
                    break;
                }
                Thread.sleep(sleeptime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 尝试获取锁，子类实现
     */
    protected abstract boolean tryLock();

    /**
     * 解锁：删除key
     */
    @Override
    public abstract void unlock();
}
